#include "library2.h"
#include "avl_tree.h"
#include "vector.h"
#include "diff_avl.h"

class Interval{
public:
	//C-tor & D-tor
	Interval() : count(0) {}
	~Interval() {}
	
	//Interface methods
	bool addInterval(const int a,const int b){
		Vector v(a,b);
		if (A.exist(v)) return false;
		A.insert(v);
		B.insert(b);
		count++;
		return true;
	}
	
	bool doesIntervalExist(const int a,const int b){
		Vector v(a,b);
		return A.exist(v);
	}
	
	bool removeInterval(const int a,const int b){
		Vector v(a,b);
		if (!A.exist(v)) return false;
		A.remove(v);
		B.remove(b);
		count--;
		return true;
	}
	
	int countIntervals(const int k){
		Vector v(k, B.getMin());
		int a_rank = A.rank(v);
		int b_rank = B.rank(k);
		if (a_rank == -1 || b_rank == -1) return -1;
		return count - a_rank - b_rank;
	}
	
	bool shiftLeftInterval(const int a, const int k){
		if (k < 1) return false;
		return A.update(a,k);
	}
	
private:
	typedef AVLTree<int, true> BTree;
	typedef DiffAVL ATree;
	
	ATree A;
	BTree B;
	int count;
};

void* init(){
	void* DS = new Interval;
	return DS;
}

void quit(void* DS){
	delete (Interval*)DS;
}

int doesIntervalExist (void* DS, int a, int b){
	return ((Interval*)DS)->doesIntervalExist(a,b) ? TRUE : FALSE;
}

int addInterval (void* DS, int a, int b){
	return ((Interval*)DS)->addInterval(a,b) ? SUCCESS : FAILURE;
}

int removeInterval (void* DS, int a, int b){
	return ((Interval*)DS)->removeInterval(a,b) ? SUCCESS : FAILURE;
}

int countIntervals (void* DS, int k){
	int res = ((Interval*)DS)->countIntervals(k);
	return (res == -1 ? 0 : res);
}

int shiftLeftInterval (void* DS, int a, int k){
	return ( (Interval*)DS)->shiftLeftInterval(a,k) ? SUCCESS : FAILURE;
}

